#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/guess-number-higher-or-lower-ii/

class Solution {
    vector<vector<int>> memory;
public:
    int getMoneyAmount(int n) {
        memory.resize(n + 1, vector<int>(n + 1));
        return dfs(1, n);
    }

    int dfs(int left, int right)
    {
        if (left >= right) return 0;
        if (memory[left][right] != 0) return memory[left][right];
        int ret = INT_MAX;

        for (int head = left; head < right; head++)
        {
            int x = dfs(left, head - 1);
            int y = dfs(head + 1, right);
            ret = min(ret, head + max(x, y));
        }
        memory[left][right] = ret;
        return ret;
    }
};